<template>
  <div>
    <van-nav-bar title="商品详情" left-arrow @click-left="onClickLeft" fixed />
    <van-row>
      <van-col class="img-box" span="24"
        ><img :src="goodsInfo.picUrl" alt=""
      /></van-col>
    </van-row>
    <van-row>
      <!-- <div class="goods-price">{{'￥'+ fullPrice}}</div> -->
      <div class="goods-top">
        <van-cell :title="'￥' + fullPrice" title-class="goods-price">
          <template #right-icon>
            <!-- <van-icon
              class="collect-icon"
              @click="collectProject"
              :name="'star'"
            /> -->
            <van-icon @click="collect" class="collect-icon" :name="iconName" />
          </template>
        </van-cell>
        <h6 class="goods-title">{{ goodsInfo.name }}</h6>
      </div>
    </van-row>
    <div class="goods-intro">——商品介绍——</div>
    <div class="pro-details">
      <p>{{ goodsInfo.brief }}</p>
      <ul>
        <li v-for="(item, index) in goodsInfo.gallery" :key="index">
          <img :src="item" alt="" />
        </li>
      </ul>

      <div class="more-intro">
        <div class="more-i-item" v-for="(item, index) in issues" :key="index">
          <span>{{ item.id }}.{{ item.question }}</span>
          <div class="ans">{{ item.answer }}</div>
        </div>
      </div>
    </div>

    <van-divider
      :style="{ color: '#333', borderColor: '#333', padding: '30px 100px' }"
    >
      更多推荐
    </van-divider>

    <div class="new-goods-list">
      <goods-item
        class="new-goods-list-item"
        @click.native="openGoods(item)"
        v-for="(item, index) in moreGoods"
        :key="index"
        :goodsInfo="item"
      />
    </div>

    <van-goods-action>
      <van-goods-action-icon
        @touchend.native="openCart"
        icon="shopping-cart-o"
        text="购物车"
      />
      <van-goods-action-button
        color="#1989fa"
        type="warning"
        text="立即购买"
        @click="chooseSpec"
      />
    </van-goods-action>

    <!-- 商品规格 -->

    <van-sku
      v-model="show"
      reset-stepper-on-hide
      :sku="sku"
      :goods="goods"
      :goods-id="goodId"
      :custom-stepper-config="customStepperConfig"
      @buy-clicked="onBuyClicked"
      @add-cart="onAddCartClicked"
    />
  </div>
</template>

<script>
import {
  getGoodsDetail,
  addShoppingCart,
  addOrDelCollect,
  cacheInfo,
} from "@/network/index.js";
import GoodsItem from "@/views/Home/HomeChildren/GoodsItem.vue";

import {
  NavBar,
  Col,
  Row,
  Cell,
  CellGroup,
  Icon,
  GoodsAction,
  GoodsActionIcon,
  GoodsActionButton,
  Divider,
  sku,
  Toast,
} from "vant";

export default {
  name: "GoodsDetail",
  data() {
    return {
      goodsInfo: {},
      skuId: 0,
      num: 1,
      iconName: "like-o",
      issues: [],
      moreGoods: [],
      show: false,
      goodId: 0, //规格id
      sku: {
        // 数据结构见下方文档
        tree: [
          {
            k: "规格",
            k_s: "s1",
            v: [
              {
                id: "1",
                name: "标准",
              },
            ],
          },
        ],
        // 所有 sku 的组合列表
        list: [
          {
            id: 0,
            s1: "1",
            price: 10000,
            stock_num: 1100000, // 当前 sku 组合对应的库存
          },
        ],
        price: "", // 默认价格（单位元）
        stock_num: 2270000000000,
      },
      goods: {
        // 数据结构见下方文档
        picture: "",
      },
      stock_num: 0,
      customStepperConfig: {
        handleStepperChange: (currentValue) => {
          this.num = currentValue;
        },
      },
    };
  },
  computed: {
    fullPrice() {
      const hasPrice = typeof this.goodsInfo.retailPrice !== "undefined";
      return hasPrice ? this.goodsInfo.retailPrice.toFixed(2) : "";
    },
  },
  components: {
    GoodsItem,
    [NavBar.name]: NavBar,
    [Col.name]: Col,
    [Row.name]: Row,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [Icon.name]: Icon,
    [GoodsAction.name]: GoodsAction,
    [GoodsActionIcon.name]: GoodsActionIcon,
    [GoodsActionButton.name]: GoodsActionButton,
    [Divider.name]: Divider,
    [sku.name]: sku,
    [Toast.name]: Toast,
  },
  watch: {
    $route(val, oldVal) {
      //监听路由
      if (val.path === "/GoodsDetail") {
        //如果路由发生改变且路由为GoodsDetail
        this.getInfo(); //重新根据路由参数获取数据
      }
    },
  },
  methods: {
    onClickLeft() {
      //返回上一页
      this.$router.back();
    },
    async collect() {
      if (this.$store.state.userInfo) {
        //优先判断是否已经登录如果已经登录了
        if (this.iconName === "like-o") {
          const info = {
            type: 0,
            id: this.goodsInfo.id,
          };
          const { data } = await addOrDelCollect(info);
          if (data.errno === 0) {
            Toast({
              message: "收藏成功",
              icon: "like",
            });
            this.iconName = "like";
          }
        } else {
          const info = {
            type: 0,
            id: this.goodsInfo.id,
          };
          const { data } = await addOrDelCollect(info);
          if (data.errno === 0) {
            Toast({
              message: "取消收藏成功",
              icon: "like",
            });
            this.iconName = "like-o";
          }
        }
      } else {
        Toast.fail('请登录后再进行操作');
      }
    },
    async collectProject() {
      //收藏专辑
    },
    //打开商品详情信息页
    openGoods(item) {
      this.$router.push({
        //重载页面且重新传参
        name: "GoodsDetail",
        query: {
          id: item.id,
        },
      });
      this.$router.go(0); //刷新页面
    },
    async getInfo() {
      //根据路由携带参数获取信息方法
      const {
        data: { data },
      } = await getGoodsDetail({ id: this.$route.query.id });
      console.log(data);
      this.goodsInfo = data.info;
      this.issues = data.issue;
      this.moreGoods = data.relatedGoods;
      this.goods.picture = data.info.picUrl;
      this.skuId = data.productList[0].id;
      this.sku.list[0].price = (data.info.retailPrice * 100).toFixed(2);
      this.sku.list[0].stock_num = data.productList[0].number
      this.goodId = data.productList[0].id;
      // this.stock_num = data.productList[0].number
      if (data.userHasCollect === 1) {
        this.iconName = "like";
      }
    },
    //选择规格
    chooseSpec() {
      this.show = !this.show;
    },
    openCart() {
      // console.log(1);
      this.$router.push({name: 'ShoppingCart'})
    },
    //购买点击
    async onBuyClicked() {
      const info = {
        goodsId: this.goodsInfo.id,
        number: this.num,
        productId: this.skuId,
      };
      // console.log(info);
      const res = await cacheInfo(info);
      console.log(res);
      if (res.data.errno === 0) {
        this.$store.commit('setAtOnceId',this.goodsInfo.id)
        this.$router.push({
          name: "OrderCreate",
          query: { 
            cartId: res.data.data,
            // info: this.goodsInfo,
            number: this.num,
            },
          
        });
      }
    },
    //加入购物车点击
    async onAddCartClicked() {
      if (this.$store.state.userInfo) {
        const info = {
          goodsId: this.goodsInfo.id,
          number: this.num,
          productId: this.goodId,
        };
        const { data } = await addShoppingCart(info);
        if (data.errno === 0) {
          Toast.success("加入购物车成功!");
          this.show = !this.show;
        }
      } else {
        Toast.fail("请登录后再进行操作");
        this.$router.push({ name: "Login" });
      }
    },
  },
  created() {
    //组件创建时调用
    this.getInfo();
  },
  mounted() {},
};
</script>

<style lang="less" scoped>
.img-box {
  height: 350px;
  width: 100%;
  img {
    width: 100%;
    height: 100%;
  }
}
.goods-price {
  margin-bottom: 5px;
  color: #d43737;
  font-size: 26px;
  padding: 0 5px;
}
.goods-title {
  line-height: 30px;

  margin: 0;
  padding: 0 20px;
  font-size: 16px;
  background-color: #fff;
  border-radius: 0 0 25px 25px;
}
.goods-top {
  background-color: rgb(245, 245, 245);

  height: 120px;
}
.collect-icon {
  color: #d43737;
  font-size: 20px;
}
.goods-intro {
  font-size: 14px;
  line-height: 40px;
  text-align: center;
  border-radius: 25px 25px 0 0;
}
.goods-img-list {
  width: 100%;
  .goods-img {
    width: 100%;
  }
}
.pro-details {
  width: 100%;
  p {
    font-size: 16px;
    padding-left: 20px;
  }
  ul {
    width: 100%;
    li {
      width: 100%;
      img {
        width: 100%;
      }
    }
  }
  .more-intro {
    .more-i-item {
      margin: 5px 0;
      span {
        font-size: 16px;
        font-weight: bolder;
        padding: 0 5px;
      }

      .ans {
        font-size: 14px;
        padding: 0 5px;
      }
    }
  }
}
.new-goods-list {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
  .new-goods-list-item {
    width: 45%;
    height: 217px;
    margin-bottom: 10px;
  }
}
</style>

